#include "toml-c.h"

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>


bool g_debug_on = false;

#define THEME_DEFAULT   ""

const char *ps1 = NULL;

#define debug(fmt, arg...) \
    do { \
        if (g_debug_on) \
            printf("[debug] %s +%d : " fmt "\n", __FILE__, __LINE__, ## arg); \
    } while(0)

int load(char *name, char *buf, int max)
{
    int fd = open(name, O_RDONLY);
    if (fd < 0) {
        printf("can't open file\n");
        return -1;
    }

    int ret = read(fd, buf, max);
    if (ret <= 0) {
        printf("read failed\n");
        return -1;
    }

    close(fd);
    return 0;
}


int get_config(char *conf_dir, char *user_theme)
{
}

int main(int argc, char *argv[])
{
    char ps[256];
    char errbuf[200];

    char buf[1024 * 1024] = {0};
    if (argc == 1) {
        printf("./a.out xxx.toml\n");
        return -1;
    }

    char *name = argv[1];

    char *theme = getenv("BASHLINE_THEME");

    load(name, buf, sizeof(buf));

    toml_table_t *root = toml_parse(buf, errbuf, sizeof(errbuf));
    if (!root) {
        fprintf(stderr, "ERROR: %s\n", errbuf);
        exit(-1);
    }

    if (theme == NULL) {
        toml_table_t *tab_bashline = toml_table_table(root, "bashline"); // find subtable from table [theme]
        if (!tab_bashline) {
            printf("can't find any theme\n");
            return -1;
        }

        toml_value_t val_theme = toml_table_string(tab_bashline, "theme");
        if (!val_theme.ok) {
            printf("key: theme\n");
            return -1;
        }

        theme = val_theme.u.s;
    }

    printf("theme: %s\n", theme); 

    /*
     * find table in table
     * [father]
     * [child1]
     * [child2]
     *   OR
     * [father.child1]
     * [father.child2]
     */

    toml_table_t *tab_theme = toml_table_table(root, "themes"); // find subtable from table [theme]
    if (!tab_theme) {
        printf("can't find any theme\n");
        return -1;
    }

    toml_table_t *tab = toml_table_table(tab_theme, theme); // find subtable from table [theme]
    if (!tab) {
        printf("can't find any tab\n");
        return -1;
    }

    int l = toml_table_len(tab);
    printf("len: %d\n", l);
    for (int i = 0; i < l; i++) {
        int keylen;
        const char *key = toml_table_key(tab, i, &keylen);
        toml_value_t val = toml_table_string(tab, key);
        if (!val.ok) {
            printf("error: val!\n");
            return -1;
        }
        printf("key #%d: %s, val: %s\n", i, key, val.u.s);
    }

    return 0;
}
